package com.ruoyix.monitor.admin.config;

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * admin 监控 安全配置
 *
 * @author Lion Li
 */
@EnableWebSecurity
public class SecurityConfig {

    private final String adminContextPath;

    public SecurityConfig(AdminServerProperties adminServerProperties) {
        this.adminContextPath = adminServerProperties.getContextPath();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(adminContextPath + "/");

        //TODO  AI
        return httpSecurity
            // 配置头部，禁用 frameOptions
            .headers(headers -> headers
                .frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)
            )
            // 授权请求
            .authorizeHttpRequests(auth -> auth
                .requestMatchers(
                    adminContextPath + "/assets/**",
                    adminContextPath + "/login",
                    "/actuator",
                    "/actuator/**",
                    "/weblog/article/getWebInfoMessage"
                ).permitAll() // 允许这些路径的访问
                .anyRequest().authenticated() // 其他请求需要认证
            )
            // 登录配置
            .formLogin(form -> form
                .loginPage(adminContextPath + "/login")
                .successHandler(successHandler)
            )
            // 登出配置
            .logout(logout -> logout
                .logoutUrl(adminContextPath + "/logout")
            )
            // 禁用 CSRF 防护
            .csrf(AbstractHttpConfigurer::disable)

            // 最后构建配置
            .build();
    }

}
